// packageStore/pages/market/promotions/detail.js
import {
  list
} from '../../../../js/modules/mall';
import {util,api,storage,dialog} from '../../../../js/util';
import {wholesaleSettings,share} from '../../../../js/modules/gloab';
import {
  promotion
} from '../../../../js/modules/market';
import authorize from '../../../../js/modules/authorize.js'
import {
  router,
  pagesInfo
} from '../../../../js/router';
import {
  profile
} from "../../../../js/modules/store.js";
import BasePage from '../../../../js/common/base-page'
import { getLengthAfterDot, isEmpty } from '../../../../js/newUtil';
import {
  getViewListSize,
  drawCanvas,
  getImgList,
} from '../../../js/canvas'

import {
  formatCanvasData
} from './canvasData'

const app = getApp();
BasePage({
  validateLogin: false,
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    id: 0,
    promoteInfo:{
      prom: {},
      name: "",
      terminal: "",
      detail: "",
      promotLadder: [],
      promoteList: []
    },
    is_search:false,
    marketSource:[],
    mainColor:'',//主题色
    showStyle:'line',
    NoLoginShowPrice:false,//
    isLogin:true,//判断是否登录
    CartName:'',
    FieldDisplayName:[],
    ClassDisplayField:{},
    GoodsUnitDisplayMode:0,
    FrontShowStockDetail:false,
    listState:true,
    hasMaket:true,
    showPosterShadow: false, //海报弹层
    saveBtn: false,//保存图片按钮
    logo: '',
    hideActivity: true, // 促销商品列表隐藏活动相关内容（拼团、预售、特价、促销活动）
    mustBuyGoods: [], // 必买商品
    minGoodsCount: 0 // 至少购买多少种商品
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 兼容扫二维码进入，并且只有一个数字（促销id）的情况
    if (options.scene) {
      let scene = options.scene
      if (!scene.includes('_') && !options.id) {
        options.id = scene
        options.scene = ''
      }
    }
    this.getData(options);
    this.getShareInfo();
    this.setData({
      showStyle:storage.get('showStyle') || 'line'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var tabindex = app.getTabBarindex();
    this.setData({
      tabindex:tabindex
    })
    var that=this;
    var p = app.globalData.product_list;
    var rule_id=p.rule_id||-1;
    // if (p.bid.length>0){
    //   this.productlist.setData({
    //     bid: p.bid
    //   });
    // }
    // if (p.cid > 0) {
    //   this.productlist.setData({
    //     cid: p.cid,
    //     selectedCategoryId:p.cid
    //   });
    // }
    if (p.rule_id > 0) {
      this.productlist.setData({
        rule_id: p.rule_id
      }); 
    }
    if (p.tag_id>0){
      this.productlist.setData({
        tag_id: p.tag_id
      });
    }
    if (p.index_search_keyword && p.index_search_keyword.length>0) {
      this.productlist.setData({
        keywords: p.index_search_keyword
      });
    }
    if (p.ikcqr && p.ikcqr.length>0) {
      this.productlist.setData({
        ikcqr: p.ikcqr
      });
    }
    this.getWholesaleConfig();
    
    this.setData({
      mainColor:api.titleColor||"#e56b14",
      Currency:api.Currency || '￥',
      isLogin:authorize.isLogin('store')
    });
  },
   /**加载商品类的配置项参数 */
   getWholesaleConfig() {
    var that = this;
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    var isLoadList=false;
    list.getWholesaleConfigs(
      fkid,
      fkflag,
      function (content) {
        var fieldDisplayName = content.FieldDisplayName?content.FieldDisplayName.split(','):[];
        var mClassDisplayField = content.MClassDisplayField?content.MClassDisplayField.split('|'):[];
        var classDisplayField = {Price:false,ProductCode:false,PackageSpec:false,BuyLimit:false,BarCode:false,PromotLadder:false,Sell:false};
        for(var i = 0;i<mClassDisplayField.length;i++){
          if (mClassDisplayField[i]=='Sell') {
            classDisplayField[mClassDisplayField[i]]=content.ShowProductSells;
          } else {
            classDisplayField[mClassDisplayField[i]]=true;
          }
        }
        that.productlist.setData({
          is_search: that.data.is_search,
          quantityDigits: content.QuantityDigits,
          priceDigits: content.PriceDigits,
          enableZeroStockBuy: content.EnableZeroStockBuy,
          NotShowProductNoneOffered: content.NotShowProductNoneOffered, // 是否不显示无货商品按钮
          showRetailPrice: content.ShowRetailPrice,
          spectStyle: content.GoodsDisplayMode,
          addressAssignDepot: content.AddressAssignDepot,
          isScanty: content.IsScanty, //是否允许缺货登记
          NoLoginShowPrice:content.NoLoginShowPrice,//0：建议零售价 1：不显示价格
          CartName:api.CartName || '购物车',
          FieldDisplayName: fieldDisplayName,
          ClassDisplayField: classDisplayField,
          GoodsUnitDisplayMode: content.GoodsUnitDisplayMode,
          FrontShowStockDetail: content.FrontShowStockDetail
        },function(){
          if (!isLoadList){
            isLoadList=true;
            that.productlist.loadMain();
          }
        });
        that.setData({logo: content.LogoForMobile});
      });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    this.productlist.onPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.productlist.onReachBottom();
  },
  /**
   * 获取分享信息
   */
  getShareInfo:function(){
    let that = this;
    let {id,promoteInfo} = that.data;
    let param = {
        Proprietor:app.dns.proprietor,
        ProprietorId:app.dns.proprietorId,
        PromotId:id,
        Type:'promot'
    }
    share.getinfo(param,false,function(res){
        let shareObj = {};
        shareObj.title = res.Title || promoteInfo.name;
        shareObj.img = res.ImgSrc!=''?api.imgDomain+res.ImgSrc:'';
        that.setData({
            shareObj:shareObj
        })
    })
  },
  /**
   * 打开分享弹层
   */
  showShare: function(e) {
    var that = this;
    dialog.showModal(that, 'showModalStatus')
  },
  /**隐藏优惠劵层 */
  hideModal() {
    let that = this;
    dialog.hideModal(that, 'showModalStatus')
  },
  /**
   * 显示海报
   */
  showPoster: function () {
    dialog.hideModal(this, 'showModalStatus')
    this.drawPicture();
    this.setData({
      showPosterShadow: true
    })
  },
  /**
   * 关闭海报
   */
  hidePoster: function () {
    this.setData({
      showPosterShadow: false,
      saveBtn: false
    })
  },
  //绘制海报
  drawPicture: function () {
    let that = this;
    //获取设备信息高度。计算出其他的高度等
    wx.getSystemInfo({
      success: function (res) {
        //调整海报清晰度
        that.setData({
          windowWidth: res.windowWidth * 2,
          windowHeight: res.windowHeight * 2,
          canvasId: "canvas"
        });
        res.windowWidth = res.windowWidth * 2;
        res.windowHeight = res.windowHeight * 2;
        that.initData(res);
      }
    });
  },
  initData: function (res) {
    let that = this;
    that.setData({
      normalPageX:
        (res.windowWidth * 0.74 - res.windowWidth * 0.67) / 2, //左边文本图片X轴位置
      boxWidth: res.windowWidth * 0.74, //分享图片box宽度
      boxheight: res.windowWidth * (0.222 + 0.72 + 0.192) + 20, //分享图片box高度
      boxPageY: 0, //boxY轴位置
      codeWidth: res.windowWidth * 0.50, //小程序码图片宽度
      codeHeight: res.windowWidth * 0.50, //小程序码图片高度
      codePageY:res.windowWidth * 0.15, //小程序码Y轴位置
      pricePageY:res.windowWidth * 0.85 + 30 , //价格Y轴位置
      titlePageY:res.windowWidth * 0.85 + 70, //标题Y轴位置
      logoWidth: res.windowWidth * 0.05 * 5.5,
      logoHeight: res.windowWidth * 0.05,
    });
    if (that.data.logo != "" && that.data.downlogo == "") {
      wx.downloadFile({
        url: that.data.imgDomain.replace("http://","https://") + that.data.logo,
        success: function (res) {
          that.setData({
            downlogo: res.tempFilePath
          });
        },
        fail: function (err) {
          util.tips(err.errMsg);
          console.log(err.errMsg,'====1');
         }
      });
    }
    that.downloadSkuQrCode();
  },
  //下载小程序码
  downloadSkuQrCode: function () { 
    let that = this;
    const currentRoute = that.getCurrentPageUrlWithArgs();
    console.log(currentRoute)
    profile.load_wx_qrcode(currentRoute, function (content) {
      if (content != "") {
        var url = "data:image/png;base64," + content;
        that.setData({
          preQR: url
        })
        util.base64src(url, function (res) {
          url = res;
          that.setData({
            qrCode: url
          });
          that.renderCanvas()
          // that.createNewImg();
        });
        // console.log(that.data.preQR,'----qr');
      } else {
        that.setData({
          showPosterShadow: false
        }, function () {
          util.tips("未能生成小程序码");
          return;
        })
      }
    });
  },
  getCurrentPageUrlWithArgs: function () {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = currentPage.route
    const options = currentPage.options
    let urlWithArgs = options.id;
    // 生成二维码中添加分享者信息
    var storeInfo = authorize.getEntity();
    if (storeInfo) {
      urlWithArgs = urlWithArgs + '_' + storeInfo.fkFlag + "_" + storeInfo.fkId + "_" + storeInfo.manager.ManagerId
    } else {
      urlWithArgs = urlWithArgs + '_0_0_0'
    }
    return {
      url,
      urlWithArgs
    }
  },
  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    wx.previewImage({
      urls: [that.data.tempFilePath],
    });
    wx.saveImageToPhotosAlbum({
      filePath: that.data.tempFilePath,
      success(res) {
        wx.hideLoading();
        // utils.aiCardActionRecord(19);
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) { }
          },
          fail: function (res) { }
        })
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: "保存失败",
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  renderCanvas() {
    let t = this
    let scale = 2
    getViewListSize(['.center-shadow .cont']).then((res) => {
      let {
        imgDomain,
        logo,
        promoteInfo,
        preQR,
        qrCode
      } = this.data
      let item = {}
      if (res.length > 0) {
        if (res[0].list && res[0].list.length > 0) {
          item = res[0].list[0][0]
        }
      }
      t.setData({
        boxHeight: item.height * scale,
        boxWidth: item.width * scale
      })
      let data = {
        imgDomain,
        logo,
        promoteInfo,
        preQR,
        qrCode,
        scale: scale
      }
      let newData = formatCanvasData(data)
      console.log(newData)
      drawCanvas(newData)
      getImgList().then((res) => {
        if(!isEmpty(res)) {
          t.setData({
            tempFilePath: res[0].src,
            saveBtn: true
          })
        }
      })
    })
  },
  // 根据文字多少动态计算高度，然后依次画出矩形，文字，横线和小程序码。
  createNewImg: function () {
    let that = this;
    let ctx = wx.createCanvasContext(that.data.canvasId);
    let contentHeight = that.data.boxheight;
    that.drawSquare(ctx, contentHeight);
    that.setData({
      contentHeight: contentHeight
    });
    ctx.drawImage(that.data.downlogo, (that.data.boxWidth - that.data.logoWidth) / 2+10,that.data.logoHeight+20, 120, 70)
    console.log(that.data.logoHeight,'----logo',that.data.logoHeight);
    ctx.setFillStyle("#000");
    ctx.font = "normal normal 24px sans-serif";
    ctx.textAlign = "center";
    ctx.fillText(that.data.promoteInfo.name, that.data.logoWidth+40, that.data.logoHeight+120);
    ctx.font = "normal normal 20px sans-serif";
    ctx.fillText(that.data.promoteInfo.detail, that.data.logoWidth+46, that.data.logoHeight+150);
    let itemIndex = 0, lastItemY = that.data.logoHeight+150;
    for (let i = 0; i < that.data.promoteInfo.promotLadder.length; i++) {
      let pItem = that.data.promoteInfo.promotLadder[i]
      for(let j = 0; j < pItem.list.length; j++) {
          let lItem = pItem.list[j]
          lastItemY = that.data.logoHeight+180+(itemIndex*30);
          ctx.fillText(lItem.name, that.data.logoWidth+46, lastItemY);
      }
    }
    ctx.fillText(that.data.promoteInfo.prom.StartTime+" - "+that.data.promoteInfo.prom.EndTime, that.data.logoWidth+46, lastItemY+50);
    // 填充小程序码
    ctx.drawImage(
      that.data.qrCode,
      that.data.normalPageX+50,
      that.data.codePageY+110,
      that.data.codeWidth,
      that.data.codeWidth
      // that.data.codeHeight
    );
    // 填充长按立即购买文本
    ctx.setFillStyle("#333");
    ctx.font = "normal normal 18px sans-serif";
    ctx.fillText(
      "扫描/长按识别",that.data.logoWidth,that.data.codePageY + that.data.codeWidth + 140
    );
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          that.setData({
            tempFilePath,
            saveBtn: true
          })
          // console.log(that.data.saveBtn,'-----');
        },
        fail: function (err) {
          console.info(err);
        }
      });
    }); //绘制到canvas
  },
  //画矩形，也是整块画布的大小，宽度是屏幕宽度，高度根据内容多少来动态设置。
  drawSquare: function (ctx, height) {
    let that = this;
    ctx.rect(
      0,
      0,
      that.data.boxWidth,
      height
    );
    ctx.setFillStyle("#fff");
    ctx.fill();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    let {id,shareObj} = this.data;
    let storeInfo = authorize.getEntity();
    let scene="";
    if(storeInfo){
      scene=storeInfo.fkFlag+"_"+storeInfo.fkId+"_"+storeInfo.manager.ManagerId;
    } 
    let path = pagesInfo.promotionDetail.url + `?id=${id}&scene=${scene}`;
    return {
        title: shareObj.title,
        imageUrl: shareObj.img,
        path: path
    }
  },
  /**
   * 分享朋友圈（beta版本，仅限安卓手机）
   */
  onShareTimeline:function(){
    let {id,shareObj} = this.data;
    let storeInfo = authorize.getEntity();
    let scene="";
    if(storeInfo){
      scene=storeInfo.fkFlag+"_"+storeInfo.fkId+"_"+storeInfo.manager.ManagerId;
    } 
    let path = `id=${id}&scene=${scene}`;
    return {
        title: shareObj.title,
        imageUrl: shareObj.img,
        query: path
    }
  },
  /**
   * 获取数据
   */
  getData:function(options){
    let that = this;
    if (options.id <= 0 && !options.scene) {
      //数据加载错误
      return;
    }
    //解析扫描促销详情小程序码中的scene
    if (options.scene && options.scene.indexOf("_")>-1) {
      let scene = decodeURIComponent(options.scene);
      let sceneArray = scene.split("_");
      if(sceneArray.length>0){
        // 当scene为4个数字相连时，第一个为促销id,剩下的为分享者信息
        if (sceneArray.length == 4) {
          options.id = sceneArray[0]
          sceneArray = sceneArray.slice(1)
          options.ikcqr = sceneArray.join('_')
        } else {
          options.ikcqr = scene;
        }
      }
    }
    this.setData({ id: options.id });
    this.productlist = this.selectComponent("#productlist");
    app.globalData.product_list.rule_id = options.id;
    app.globalData.product_list.ikcqr = options.ikcqr;
    promotion.getPromotionDetail({promId:options.id},function(content){
      that.analysisData(content[0]);
    })
  },
  /**
   * 解析数据
   */
  delRepeatData(arr){
    const map = {}
    const nList = []
    for (let i = 0; i < arr.length; i++) {
        const item = arr[i]
        // 如果map没有则在新nList中添加
        if (!map[item.goodsId]) {
            nList.push({
            ...item,
            })
            map[item.goodsId] = item
        } else {
            // 遍历nList
            for (let j = 0; j < nList.length; j++) {
                const nItem = nList[j]
                // 如果商品相同 合并detail和name字段
                if (nItem.goodsId == item.goodsId) {
                    nItem.list = [...nItem.list, ...item.list ]
                    break
                }
            }
        }
    }
    return nList
  },
  /**
   * @param {*} unit 商品单位，满多少商品单位赠送
   */
  formaterNames(discountMode, item, config, discountCalcType, tinfo, unit = ''){
    var tmp = "{0}{1}{2}";
    let name = ''
    // 折扣保留小数点后位数,最多2位
    let discountValue = item.DiscountValue
    discountValue = util.precisionX(discountValue, 10)
    let fixed = getLengthAfterDot(discountValue)
    fixed = fixed > 2 ? 2 : fixed
    discountValue = discountValue.toFixed(fixed)
    switch (discountMode) {
        case 1:
            name = tmp.format("金额" + (discountCalcType == 1 ? "每" : "") + "满" + parseFloat(item.MinimumValue) + "元", "，立减" + parseFloat(item.DiscountValue) + "元", tinfo)
        break;
        case 2:
            name = tmp.format("金额" + (discountCalcType == 1 ? "每" : "") + "满" + parseFloat(item.MinimumValue) + "元", "，打" + discountValue + "折", tinfo)
        break;
        case 3:
            name = tmp.format( "金额" + (discountCalcType == 1 ? "每" : "") + "满" + parseFloat(item.MinimumValue) + "元", "", tinfo)
        break;
        case 4:
            name = tmp.format("数量" + (discountCalcType == 1 ? "每" : "") + "满" + parseFloat(item.MinimumValue, 0), unit + "，立减" + parseFloat(item.DiscountValue) + "元", tinfo)
        break;
        case 5:
            name = tmp.format("数量" + (discountCalcType == 1 ? "每" : "") + "满" + parseFloat(item.MinimumValue, 0), unit + "，打" + discountValue + "折", tinfo)
        break;
        case 6:
            name = tmp.format("数量" + (discountCalcType == 1 ? "每" : "") + "满" + parseFloat(item.MinimumValue, 0), unit + "", tinfo)
        break;
        case 7:
          name = tmp.format("数量" + (discountCalcType == 1 ? "每" : "") + "满" + parseFloat(item.MinimumValue, 0), unit + "，单价立降" + parseFloat(item.DiscountValue) + "元", tinfo)
        break;
    }
    return name
  },
  ladderOptions(item, prom, discountMode, discountCalcType, config){
    const that = this
    var ladder = {
        list: [],
        title: '',
        goodsId: item.GoodsId
    };
    // EnableSkuMode为1时获取商品名称
    if(prom.EnableSkuMode === 1) {
        ladder.title = that.goodsList(item.GoodsId,prom.EnrollProduct)
    }
    var tinfo = "";
    let list = [],FreeFreightTrue = false;
    let unitName = '' // 商品单位
    if (item.Gifts && item.Gifts != "") {
        // 单独设置的商品，直接加上其单位
        if (prom.EnableSkuMode == 1) {
          unitName = item.Unit || '' // 商品单位
        } else {
          // 非单独设置并且为商品组合时，显示单位
          if (discountMode == 4 || discountMode == 5 || discountMode == 6 || discountMode == 7) {
            if (item.PromotUnitType == 2) {
              unitName = '销售单位'
            } else {
              unitName = '基础单位'
            }
          }
        }
        if (item.GiftType == 1) {
          tinfo += '，送本品'
          if (item.GiftsNum > 0) {
            tinfo += item.GiftsNum
          }
          // 单独设置的商品，直接加上其单位
          if (prom.EnableSkuMode == 1) {
            tinfo += item.GiftsUnit || item.Unit || '' // 赠送的商品单位
          }
        } else {
          if (item.GiveMethod == 1) {
            // 选赠品
            tinfo += `，任选${item.GiveCount || ''}种赠品`
          } else {
            // 赠品
            // GiftsNumTotal：赠品总数
            tinfo += '，送赠品'
            tinfo += item.GiftsNumTotal || ''
          }
        }
        let opt = {name:'赠品', data:[]};
        let gifts = item.GiftsList || [];
        for (let j = 0; j < gifts.length; j++) {
            let gift = gifts[j];
            opt.data.push({name:gift.Name || "",num:gift.Num || 1, unit: gift.Unit});
        }
        if (item.FreeFreight == 1) {
          FreeFreightTrue = true;
          tinfo += "，免邮";
        }
        let name = this.formaterNames(discountMode, item, config, discountCalcType, tinfo, unitName)
        list.push({ name: name,tips: [opt] })
    }
    if (item.Coupons && item.Coupons != "") {
        tinfo += "，送优惠劵";
        console.log(unitName)
        let opt = { name:'优惠券',data:[]};
        let coupons = item.CouponsList || [];
        for (let j = 0; j < coupons.length; j++) {
            let coupon = coupons[j];
            opt.data.push({name:coupon.Name || "",num:coupon.Num || 1});
        }
        if (item.FreeFreight == 1 && !FreeFreightTrue) {
            tinfo += "，免邮";
        }
        let name = this.formaterNames(discountMode, item, config, discountCalcType, tinfo, unitName)
        if(list.length > 0) {
            list[0].name = name
            list[0].tips.push(opt)
        } else {
            list.push({ name: name,tips: [opt] })
        }
        
    }
    if(item.Coupons == "" && item.Gifts == "") {
        let name = this.formaterNames(discountMode, item, config, discountCalcType, tinfo, unitName)
        let opt = { name:name,data:[]};
        if(list.length > 0) {
            list[0].tips.push(opt)
        } else {
            list.push({ name: name,tips: [opt] })
        }
    }
    ladder.list = list
    return ladder
  },
  /**
   * 满赠，非按商品单独设置时
   * 
   * 处理EnableSkuMode !=1 的数据
   */
  normalData(prom, promotLadder, discountMode, discountCalcType, config, len) {
    const that = this
    let list = []
    for (var i = 0; i < len; i++) {
        let item = promotLadder[i];
        const ladder = that.ladderOptions(item, prom, discountMode, discountCalcType, config)
        list.push(ladder)
    }
    return list
  },
  /**
   * 赠送商品，按商品单独设置时
   * 
   * 处理EnableSkuMode == 1的数据
   */
  dealModeData(prom, promotLadder, discountMode, discountCalcType, config, len) {
    const that = this
    const productList = prom.EnrollProduct
    let list = []
    for (let i = 0; i < productList.length; i++) {
        let pItem = productList[i]
        for(let j = 0; j < len; j++) {
            let lItem = promotLadder[j]
            if(pItem.GoodsId === lItem.GoodsId) {
                const ladder = that.ladderOptions(lItem, prom, discountMode, discountCalcType, config)
                list.push(ladder)
            }
        }
    }
    let finalList = list
    // 处理多个商品有的促销信息
    if(productList.length >= 1) {
        finalList = that.delRepeatData(list)
    } else {
        // finalList.map((item,index)=>{
        //     if(index > 0) {
        //         item.title = ''
        //     }
        // })
    }
    return finalList
  },
  analysisData:function(prom){
    var that = this;
    let { promoteInfo } = this.data; 
    var config = wholesaleSettings.getConfig();
    var terminal = prom.Terminal || 0;
    var discountMode = prom.DiscountMode || 0;
    var discountCalcType = prom.DiscountCalcType || 0;
    var promotionType = prom.PromotionType || 0;
    var promotLadder = prom.PromotLadder || [];
    let mustBuyGoods = [] // 必买商品
    let minGoodsCount = 0 // 至少购买多少种商品
    // 组合促销，才需要显示 是否满足必买商品规则 和 最少参与SKU数
    if (promotionType == 2) {
      mustBuyGoods = prom.MustBuyGoods || []
      minGoodsCount = prom.MinGoodsCount || 0
    }
    let terminalName = "";
    if (terminal == 1) {
        terminalName = "（限PC端）";
    } else if (terminal == 2) {
        terminalName = "（限移动端）";
    } else {
        terminalName = "（不限终端）";
    }
    promoteInfo.prom = prom;
    promoteInfo.name = prom.Name || "";
    promoteInfo.terminal = terminalName || "";
    if (discountMode == 1 || discountMode == 4) {
        promoteInfo.detail = (promotionType == 2 ? "商品组合" : "单品") + "满减";
    } else if (discountMode == 2 || discountMode == 5) {
        promoteInfo.detail = (promotionType == 2 ? "商品组合" : "单品") + "打折";
    } else if (discountMode == 3 || discountMode == 6){
        promoteInfo.detail = (promotionType == 2 ? "商品组合" : "单品") + "满赠";
    } else if (discountMode == 7) {
      promoteInfo.detail = (promotionType == 2 ? "商品组合" : "单品") + "满降";
    }
    promoteInfo.promotLadder = [];

    if (promotLadder.length > 0) {
        var mode = prom.EnableSkuMode;
        var len = promotLadder.length;
        if(discountCalcType==1 && mode != 1){
            len = 1;
        }
        let finalData
        if(mode == 1) {
            finalData = that.dealModeData(prom, promotLadder, discountMode, discountCalcType, config, len)
        } else {
            finalData = that.normalData(prom, promotLadder, discountMode, discountCalcType, config, len) 
        }
        promoteInfo.promotLadder = finalData
    }
    promoteInfo.promoteList = [];
    // promoteInfo.promoteList.push({name:'活动期限', type: "Term", values:[prom.StartTime+" - "+prom.EndTime]});

    let entity = authorize.getEntity();
    if (entity&&(entity.fkFlag == 2 || entity.fkFlag == 7)) {
        let customers = [];
        let customerType = "";
        let customerList = [];
        if (prom.CustomerIds && prom.Customers && prom.Customers.length > 0) {
            customerType = "Customer";
            let customerIds = prom.CustomerIds.split(",");
            for (let j = 0; j < prom.Customers.length; j++) {
                let customer = prom.Customers[j];
                if (customerIds.indexOf(String(customer.Id)) > -1) {
                    if (j == 0) {
                        customers.push(customer.Name);
                    }
                    customerList.push(customer);
                }
            }
        }
        if (prom.UseLevelIds && prom.UseLevels && prom.UseLevels.length > 0) {
            customerType = "Level";
            let levelIds = prom.UseLevelIds.split("|");
            for (let j = 0; j < prom.UseLevels.length; j++) {
                let level = prom.UseLevels[j];
                if (levelIds.indexOf(String(level.Id)) > -1) {
                    customers.push(level.Name);
                    customerList.push(level);
                }
            }
        }
        if (prom.UseTypeIds && prom.UseTypes && prom.UseTypes.length > 0) {
            customerType = "Type";
            let typeIds = prom.UseTypeIds.split("|");
            for (let j = 0; j < prom.UseTypes.length; j++) {
                let type = prom.UseTypes[j];
                if (typeIds.indexOf(String(type.Id)) > -1) {
                    customers.push(type.TypeName);
                    customerList.push(type);
                }
            }
        }
        promoteInfo.promoteList.push({name:'活动对象', type: customerType, values:customers, list:customerList});

        let products = [];
        let productType = "";
        let productList = [];
        if (prom.GoodsIds && prom.Goods && prom.Goods.length > 0) {
            productType = "Goods";
            let goodsIds = prom.GoodsIds.split(",");
            for (let j = 0; j < prom.Goods.length; j++) {
                let goods = prom.Goods[j];
                if (goodsIds.indexOf(String(goods.Id)) > -1) {
                    if (j == 0) {
                        products.push(goods.Name);
                    }
                    productList.push(goods);
                }
            }
            console.log(products,'---customerList');
        }
        if (prom.Brands && prom.EnrollScopeToBrand && prom.EnrollScopeToBrand.length > 0) {
            productType = "Brand";
            let brandIds = prom.Brands.split("|");
            for (let j = 0; j < prom.EnrollScopeToBrand.length; j++) {
                let brand = prom.EnrollScopeToBrand[j];
                if (brandIds.indexOf(String(brand.RelateId)) > -1) {
                    products.push(brand.Name);
                    productList.push(brand);
                }
            }
        }
        if (prom.Categorys && prom.EnrollScopeToCategory && prom.EnrollScopeToCategory.length > 0) {
            productType = "Category";
            let categoryIds = prom.Categorys.split(",");
            for (let j = 0; j < prom.EnrollScopeToCategory.length; j++) {
                let category = prom.EnrollScopeToCategory[j];
                if (categoryIds.indexOf(String(category.Id)) > -1) {
                    products.push(category.CateName);
                    productList.push(category);
                }
            }
        }
        if (products.length == 0) {
            productType = "Category";
            products.push("全部商品");
        }
        promoteInfo.promoteList.push({name:'活动商品', type: productType, values:products, list:productList});
    }else {
        // let products = ["查看活动商品"];
        // let productType = "Product";
        // let productList = [];
        // promoteInfo.promoteList.push({name:'活动商品', type: productType, values:products, list:productList});
    }
    // console.log('=======================', promoteInfo)
    this.setData({ 
      promoteInfo: promoteInfo,
      mustBuyGoods,
      minGoodsCount
    },function(){
    //   console.log(this.data.promoteInfo,'-------');
    });
  },
  goodsList:function(goodId,goodList,title){
      title = '';
      for(var i=0;i<goodList.length;i++){
          if(goodList[i].GoodsId == goodId){
            if (goodList[i].SpecValue != '无') {
              title = goodList[i].Name+'['+goodList[i].SpecValue+']'
            } else {
              title = goodList[i].Name
            }
            break
          }
      }
      return title;
  },
  /**
   * 促销活动跳转
   */
  onSkipPromotion:function(e){
    var id = e.currentTarget.dataset.id;
    app.globalData.product_list.rule_id = id;
    router.navigate({
      path: "productList"
    })
  }

})